package com.syh.jn.scm.infrastructure.repository.impl.upstream.sale;

import cn.redscarf.commons.util.bean.ExtBeanUtils;
import cn.redscarf.commons.util.other.ExtAssert;
import cn.redscarf.commons.util.validator.ValidationUtils;
import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.core.ddd.infrastructure.repository.AbstractAggregateRepository;
import com.syh.core.expction.DataModelException;
import com.syh.jn.scm.domain.upstream.entity.sale.UpSaleReturnOrder;
import com.syh.jn.scm.domain.upstream.entity.sale.UpSaleReturnOrderItem;
import com.syh.jn.scm.domain.upstream.repository.sale.UpSaleReturnOrderRepository;
import com.syh.jn.scm.dto.upstream.sale.UpSaleReturnOrderItemVo;
import com.syh.jn.scm.dto.upstream.sale.UpSaleReturnOrderVo;
import com.syh.jn.scm.exception.BusinessException;
import com.syh.jn.scm.infrastructure.repository.model.purchase.PurchaseReturnOrderItemModel;
import com.syh.jn.scm.infrastructure.repository.model.purchase.PurchaseReturnOrderModel;
import com.syh.jn.scm.infrastructure.repository.model.sale.SaleReturnOrderItemModel;
import com.syh.jn.scm.infrastructure.repository.model.sale.SaleReturnOrderModel;
import com.syh.jn.scm.infrastructure.repository.utils.SQLAliasGenerateUtil;
import com.syh.jn.scm.infrastructure.wrapper.BaseResolve;
import com.syh.jn.scm.infrastructure.wrapper.ResolveToSQL;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class UpSaleReturnOrderRepositoryImpl extends AbstractAggregateRepository<UpSaleReturnOrder, PurchaseReturnOrderModel, Long> implements UpSaleReturnOrderRepository {

  @Override
  public UpSaleReturnOrderVo getKeyView(Serializable key) {
    UpSaleReturnOrderVo vo = super.getKeyView(key);
    if(vo == null)
      throw new BusinessException("数据异常，销售退货单不存在");
    vo.setItems(transformSaleReturn(this.getItemsByOrderId(vo.getId())));
    return vo;
  }

  /**
   * 根据id获取明细
   *
   * @param id
   * @return
   */
  @Override
  public List<UpSaleReturnOrderItem> getItemsByOrderId(Long id) {
    StringBuffer hql = new StringBuffer();
    hql.append("from PurchaseReturnOrderItemModel model where model.purchaseReturnOrderId = ?");
    List<PurchaseReturnOrderItemModel> itemModelList = (List<PurchaseReturnOrderItemModel>) this.hibernateTemplate.find(hql.toString(), id);
    List<UpSaleReturnOrderItem> itemList = new ArrayList<>();
    itemModelList.stream().forEach(item -> {
      UpSaleReturnOrderItem upSaleReturnOrderItem = new UpSaleReturnOrderItem();
      ExtBeanUtils.copyProperties(item, upSaleReturnOrderItem);
      itemList.add(upSaleReturnOrderItem);
    });
    return itemList;
  }

  @Override
  public void updateStatus(UpSaleReturnOrder saleReturnOrder) {
    super.update(saleReturnOrder);
  }

  @Override
  public UpSaleReturnOrder getById(Long id) {
    UpSaleReturnOrder upSaleReturnOrder = super.getById(id);
    if (upSaleReturnOrder == null) {
      return upSaleReturnOrder;
    }
    upSaleReturnOrder.setItems(this.getItemsByOrderId(id));
    return upSaleReturnOrder;
  }

  /**
   * 上传单据图片
   *
   * @param order
   */
  @Override
  public void upload(UpSaleReturnOrder order) {
    super.update(order);
  }

  @Override
  public void updateOrderAndItems(UpSaleReturnOrder order) {
    PurchaseReturnOrderModel orderModel = this.hibernateTemplate.get(PurchaseReturnOrderModel.class, order.getId());
    if(orderModel == null){
      throw new DataModelException("订单不存在");
    }
    ExtBeanUtils.copyProperties(order, orderModel);
    this.hibernateTemplate.update(orderModel);
    //更新订单项
    order.getItems().forEach(orderItem -> {
      PurchaseReturnOrderItemModel model = this.hibernateTemplate.get(PurchaseReturnOrderItemModel.class, orderItem.getId());
      if(model == null){
        throw new DataModelException("对应明细不存在");
      }
      ExtBeanUtils.copyProperties(orderItem, model);
      this.hibernateTemplate.update(model);
    });
  }

  @Override
  protected SQL getViewSql() {
    return new SQL() {{
      SELECT(
              SQLAliasGenerateUtil.aliasGenerate(PurchaseReturnOrderModel.class, "upSaleReturn", null),
              "upSale.code AS purchaseOrderCode",
              "dict.NAME AS returnReasonName",
              "supplier.NAME AS businessEntityName"
      );
      FROM("T_PUR_PURCHASE_RETURN_ORDER upSaleReturn");
      LEFT_OUTER_JOIN("T_PUR_PURCHASE_ORDER upSale on upSale.ID = upSaleReturn.PURCHASE_ORDER_ID");
      LEFT_OUTER_JOIN("T_BASE_DICT dict on dict.ID = upSaleReturn.RETURN_REASON_ID");
      LEFT_OUTER_JOIN("T_BASE_SUPPLIER AS supplier ON supplier.ID = upSaleReturn.BUSINESS_ENTITY_ID");
    }};
  }

  @Override
  protected Class getViewObject() {
    return UpSaleReturnOrderVo.class;
  }

  @Override
  protected BaseResolve getViewWrapperResolve(Wrapper wrapper) {
    Map<String, String> params = new HashMap<>();
    params.put("id", "upSaleReturn.ID");
    params.put("returnCode", "upSaleReturn.RETURN_CODE");
    params.put("returnOrdState", "upSaleReturn.RETURN_ORD_STATE");
    params.put("deliveryState", "upSaleReturn.DELIVERY_STATE");
    params.put("collectState", "upSaleReturn.COLLECT_STATE");
    params.put("statementId", "upSaleReturn.STATEMENT_ID");
    params.put("upStreamCompanyId", "upSaleReturn.UP_STREAM_COMPANY_ID");
    params.put("inputDateTimestamp", "upSaleReturn.INPUT_DATE_TIMESTAMP");
    ResolveToSQL parse = new ResolveToSQL(wrapper, (propertyName) -> {
      return params.get(propertyName);
    });
    return parse;
  }


  /**
   * 内部方法  业务模型转传输对象
   *
   * @param entityList
   * @return
   */
  private List<UpSaleReturnOrderItemVo> transformSaleReturn(List<UpSaleReturnOrderItem> entityList) {
    List<UpSaleReturnOrderItemVo> voList = new ArrayList<>();
    entityList.stream().forEach((entity) -> {
      UpSaleReturnOrderItemVo vo = new UpSaleReturnOrderItemVo();
      ExtBeanUtils.copyProperties(entity, vo);
      voList.add(vo);
    });
    return voList;
  }
}
